<template>
  <div class="nav-filter" @scroll.stop>
    <div class="nav-container" @touchmove.stop>
      <template v-if="showNav">
        <slot name="nav" />
      </template>
      <div v-if="filterData.length>0" :class="['filter-bar', topClass]" @click.stop="closeHandle">
        <Item ref="item" :list="listItem" :index.sync="filterIndex" :flag.sync="filterFlag" :background-color="filterIndex===null?'#F5F6F7':'#fff'" @click.native.stop />
        <Scroll vertical class="scroll-height" :style="{'max-height':'calc(100vh - '+(offTop?offTop+120:120)+'px)'}" @click.native.stop>
          <div v-show="filterIndex!==null" class="filter-content">
            <Card :show-btns="filterFlag!=='sort'" @reset="resetHandle" @confirm="confirmHandle">
              <template v-for="(f,i) in filtersView">
                <div v-if="filterIndex!==null&&!isFilterSort" :key="i" :class="['filter-content-item',{'filter-content-item-selected':f.selected}]" @click.stop="selectedClick(f, filtersView)">
                  <span class="filter-content-text">{{ f.label }}</span>
                  <img v-show="f.selected" class="filter-content-img" :src="sectionImg">
                </div>
                <template v-else-if="filterFlag==='filter'">
                  <div :key="i" class="filter-content-title" row>
                    <span>{{ f.title }}</span>
                    <div @click.stop="foldClickHandle(f)">
                      <span>{{ isFold(f)?'更多':'收起' }}</span>
                      <svg-icon :icon-class="isFold(f)?'xiangxia-zhankai-line':'xiangshang-shouqi-line'" />
                    </div>
                  </div>
                  <template v-if="!isFold(f)">
                    <template v-if="f.type=='daterange'">
                      <div :key="f.flag + i" class="filter-content-field" row>
                        <van-field v-model="f.value1" class="cus-field" label="" left-icon="calendar-o" readonly placeholder="选择日期" @click.native="openCaledar(f)" />
                        <div class="separator" />
                        <van-field v-model="f.value2" class="cus-field" label="" left-icon="calendar-o" readonly placeholder="选择日期" @click.native="openCaledar(f)" />
                      </div>
                    </template>
                    <template v-if="f.type=='monthrange'">
                      <div :key="f.flag + i" class="filter-content-field" row>
                        <FieldDateTime
                          v-model="f.value1"
                          type="year-month"
                          class="cus-field"
                          :min-date="caledarMinDate"
                          :max-date="caledarMaxDate"
                          @change="changeFieldValues(f,'value1')"
                        />
                        <div class="separator" />
                        <FieldDateTime
                          v-model="f.value2"
                          type="year-month"
                          class="cus-field"
                          :min-date="caledarMinDate"
                          :max-date="caledarMaxDate"
                          @change="changeFieldValues(f,'value2')"
                        />
                      </div>
                    </template>
                    <template v-if="f.type==='textrange'">
                      <div :key="f.flag + i" class="filter-content-field" row>
                        <van-field
                          v-model="f.value1"
                          :type="f.fieldType || 'text'"
                          class="cus-field"
                          label=""
                          :placeholder="f.placeholder1"
                          clearable
                          format-trigger="onBlur"
                          :formatter="f.formatter || null"
                        />
                        <div class="separator" />
                        <van-field
                          v-model="f.value2"
                          :type="f.fieldType || 'text'"
                          class="cus-field"
                          label=""
                          :placeholder="f.placeholder2"
                          clearable
                          format-trigger="onBlur"
                          :formatter="f.formatter || null"
                        />
                      </div>
                    </template>
                    <template v-else>
                      <div v-for="(c,m) in f.children || []" :key="c.label + m" :class="['filter-content-item',{'filter-content-item-selected':c.selected}]" @click.stop="selectedClick(c, f)">
                        <span class="filter-content-text">{{ c.label }}</span>
                        <img v-show="c.selected" class="filter-content-img" :src="sectionImg">
                      </div>
                    </template>
                  </template>
                </template>
                <template v-else-if="filterFlag==='sort'">
                  <div v-for="(c,m) in f.children || []" :key="m" row :class="['sort-content-text',{'selected':c.selected}]" @click.stop="selectedClick(c, f)">
                    <span>{{ c.label }}</span>
                    <img v-show="c.selected" class="filter-content-selected" :src="selectedImg">
                  </div>
                </template>
              </template>
            </Card>
          </div>
        </Scroll>
      </div>
    </div>
    <!-- 过滤 -->
    <div :style="{paddingTop: height + 10 + 'px'}">
      <slot />
    </div>
    <van-calendar
      v-if="showCaladar"
      v-model="caledar.show"
      type="range"
      color="#05C4C3"
      :title="caledar.title"
      :min-date="caledarMinDate"
      :max-date="caledarMaxDate"
      :default-date="caledar.defaultData"
      :style="{'height':'500px'}"
      allow-same-day
      @confirm="onConfirmCaledar"
      @scroll.stop
    />
  </div>
</template>
<script>
import Scroll from '@/components/Scroll'
import Card from './Card'
import Item from './Item'
import FieldDateTime from '@/components/FieldDateTime'
import sectionImg from '@/assets/selection@2x.png'
import selectedImg from '@/assets/icon-yes.png'
import { mapGetters, mapMutations } from 'vuex'
import mixins from './otherMixins'
export default {
  name: 'NavFilter',
  components: {
    Card,
    Item,
    Scroll,
    FieldDateTime
  },
  mixins: [mixins],
  props: {
    offTop: {
      type: [Number, String],
      default: ''
    },
    navHeight: {
      type: Number,
      default: 204
    },
    immediateRefresh: {
      // 选择条件变化时是否立即刷新
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      numberReg: /^\d+$/,
      // 过滤选中图片
      sectionImg,
      selectedImg,
      filterIndex: null,
      filterFlag: null,
      // 临时记录本次选择，如果不点确定则关闭弹窗时清楚
      tempFiltersValue: [],
      fixedFun: null,
      height: 204,
      showNav: true
    }
  },
  computed: {
    ...mapGetters('nav', ['filterData']),
    topClass() {
      return this.filterIndex !== null ? 'top' : ''
    },
    listItem() {
      return this.updateChildren(this.filterData)
    },
    // 过滤或排序
    isFilterSort() {
      return ['filter', 'sort'].includes(this.filterFlag)
    },
    // 区分filter、sort
    filtersView() {
      let result
      if (this.numberReg.test(this.filterIndex) && !this.isFilterSort) {
        result = this.listItem[this.filterIndex].children
      } else if (this.filterFlag === 'filter') {
        result = this.listItem.filter(v => v.flag !== 'sort')
      } else if (this.filterFlag === 'sort') {
        // 排序
        result = this.listItem.filter(v => v.flag === 'sort')
      } else {
        result = []
      }
      // 商品中心特殊处理
      result = result.filter(e => {
        return e.relevanceItemShow === undefined || e.relevanceItemShow
      })
      return result
    },
    showCaladar() {
      return this.filterData.some(v => v.type === 'daterange')
    }
  },
  watch: {
    filterIndex(n) {
      if (n === null) {
        this.recoverSelected()
      }
      this.limitScroll()
    },
    '$route': {
      handler() {
        this.updateFilterData([])
        this.closeHandle()
      },
      immediate: true
    },
    filterData() {
      this.touchHandle()
    }
  },
  created() {
    this.$on('next', this.next)
    this.$on('prev', this.prev)
    this.height = this.navHeight
  },
  mounted() {
    this.fixedFun = this.$touch(this.touchHandle, this)
    this.$nextTick(() => {
      const navContainer = this.$el.querySelector('.nav-container')
      if (navContainer) {
        this.height = navContainer.getBoundingClientRect().height
      }
    })
  },
  beforeDestroy() {
    this.fixedFun()
  },
  methods: {
    ...mapMutations('nav', ['updateFilterData']),
    // 去掉所有
    cancelSelectedAll(list, type) {
      for (const item of list) {
        delete item.fold // 重置折叠收起
        if (type !== 'switch' && item.selected) {
          this.tempFiltersValue.push({
            filter: item,
            rawValue: item.selected,
            value: false
          })
        }
        this.$set(item, 'selected', false)
        const children = item.children || item.next
        if (children instanceof Array) {
          this.cancelSelectedAll(children, type)
        }
      }
    },
    // 展开收起
    foldClickHandle(f) {
      if (f.fold) {
        this.$set(f, 'fold', false)
      } else {
        this.$set(f, 'fold', true)
      }
    },
    // 是否折叠
    isFold(f) {
      if (f.fold === undefined) {
        if (f.isDefaultFolded === 1 || f.isDefaultFolded === '1') {
          // 如果fold不存在且isDefaultFolded等于1则设置fold值，解决单击更多，收起的bug
          this.$set(f, 'fold', true)
          return true
        }
        return false
      }
      return f.fold
    },
    // 选中
    selectedClick(f, obj) {
      let multiple = true
      let list = obj
      if (this.$isType(obj, 'Array') && !this.isFilterSort && this.numberReg.test(this.filterIndex)) {
        multiple = !!((this.listItem[this.filterIndex] || {}).multiple)
      } else if (this.isFilterSort && this.filterFlag === 'filter') {
        multiple = !!obj.multiple
        list = obj.children
      } else if (this.filterFlag === 'sort') {
        multiple = false
        list = obj.children
      }
      let rawSelected = f.selected
      if (!multiple && this.$isType(list, 'Array')) {
        this.cancelSelectedAll(list)
      }
      if (this.filterFlag === 'sort') {
        rawSelected = false
      }

      if (rawSelected) {
        this.$set(f, 'selected', false)
        this.tempFiltersValue.push({
          filter: f,
          rawValue: true,
          value: false
        })
      } else {
        this.$set(f, 'selected', true)
        this.tempFiltersValue.push({
          filter: f,
          rawValue: false,
          value: true
        })
      }

      // 商品中心特殊处理
      if (obj.relevanceItemIndex && obj.relevanceItemIndex.length > 0) {
        obj.relevanceItemIndex.forEach(index => {
          const selected = obj.children.some(e => e.selected)
          this.$store.commit('nav/updateRelevanceItemShow', { index, selected })
          if (!selected) {
            this.cancelSelectedAll(this.filterData[index].children || [])
          }
        })
      }

      // 重新获取商品中心过滤筛选(包括：商品搜索页筛选)
      if (['Product', 'SearchProduct', 'CustomSpuProduct'].includes(this.$route.name) || this.immediateRefresh) {
        this.broadcast('refresh', 'refresh', [obj.flag])
      }
      if (obj && obj.flag === 'sort') {
        this.$nextTick(() => {
          this.closeHandle()
        })
      }
    },
    // 更新关联filter
    updateChildren(list, tier = 0) {
      const result = []
      for (const item of list) {
        if (['textrange', 'daterange', 'monthrange'].includes(item.type)) {
          result.push(item)
          continue
        }
        if (!item.unId || !item.children || item.children.length <= 0) {
          continue
        }
        if (tier === 0) {
          result.push(item)
          result.push(...this.updateChildren(item.children, 1))
        } else {
          if (item.selected) {
            result.push(item)
          }
          result.push(...this.updateChildren(item.children, 1))
        }
      }

      return result
    },
    // 重置选择
    resetHandle() {
      if (!this.isFilterSort) {
        this.cancelSelectedAll(this.listItem[this.filterIndex].children)
      } else if (this.filterFlag === 'filter') {
        this.cancelSelectedAll(this.filtersView)
        this.filtersView.forEach(item => {
          if (['textrange', 'daterange', 'monthrange'].includes(item.type)) {
            this.$set(item, 'value1', '')
            this.$set(item, 'value2', '')
          } else if (item.type === 'text') {
            this.$set(item, 'value', '')
          }
        })
      }
      this.tempFiltersValue = []
      if (this.immediateRefresh) {
        this.broadcast('refresh', 'refresh')
      }
    },
    // 还原选中
    recoverSelected() {
      for (const t of this.tempFiltersValue) {
        this.$set(t.filter, 'selected', t.rawValue)
      }
      this.filtersView.forEach(item => {
        if (['textrange', 'daterange', 'monthrange'].includes(item.type)) {
          this.$set(item, 'value1', item.rawValue1 || '')
          this.$set(item, 'value2', item.rawValue2 || '')
        } else if (item.type === 'text') {
          this.$set(item, 'value', item.rawValue || '')
        }
      })
      this.tempFiltersValue = []
    },
    // 单击背景关闭
    closeHandle() {
      if (!this.immediateRefresh) {
        this.recoverSelected()
      } else {
        this.tempFiltersValue = []
      }
      this.filterIndex = null
      this.filterFlag = null
      if (this.$refs.item) {
        this.$refs.item.closeFlag()
      }
      this.$nextTick(() => {
        const navContainer = this.$el.querySelector('.nav-container')
        this.height = navContainer.getBoundingClientRect().height
      })
    },
    // 确定筛选
    confirmHandle() {
      this.filterData.forEach(v => {
        if (['textrange', 'daterange', 'monthrange'].includes(v.type)) {
          this.$set(v, 'rawValue1', v.value1 || '')
          this.$set(v, 'rawValue2', v.value2 || '')
        }
      })

      this.tempFiltersValue = []
      this.filterIndex = null
      this.filterFlag = null
      this.$refs.item.closeFlag()
      // 调用
      this.$nextTick(() => {
        this.broadcast('refresh', 'refresh', ['confirm']) // 商品中心成品，按确定不刷新数据
      })
    },
    // 限制滚动
    limitScroll() {
      if (this.filterIndex !== null) {
        document.body.classList.add('limit-scroll')
      } else {
        document.body.classList.remove('limit-scroll')
      }
    },
    // 滚动回调
    touchHandle(x, y) {
      if (sessionStorage.getItem('forbid')) {
        this.showNav = true
        return
      }
      if (Math.abs(x || 0) > 20 && Math.abs(y || 0) < 20) {
        this.showNav = true
      } else if (y !== undefined) {
        this.showNav = y > 20
      }
      this.$nextTick(() => {
        const navContainer = this.$el.querySelector('.nav-container')
        this.height = navContainer.getBoundingClientRect().height
      })
    }
  }
}
</script>
<style lang="less">
@color8: #888;
@color3: #333;
@colorBg: #00C8B4;
.nav-filter{
  position: relative;
  .nav-container{
    position: fixed;
    width: 100%;
    z-index: 999;
  }
  // 一级导航
  .nav-level-one{
    font-size: 14px;
    font-weight: 500;
    color: @color8;
    line-height: 20px;
    letter-spacing: 1px;
  }
  .nav-level-one + .nav-level-one{
    margin-left:30px;
  }
  .nav-level-one-active{
    position: relative;
    color: @color3;
    line-height: 22px;
    font-size: 16px;
    &::after{
      content: "";
      position: absolute;
      left: 50%;
      bottom: -5px;
      transform: translateX(-50%);
      display: block;
      width: 50%;
      height: 2px;
      background-color: @colorBg;
      border-radius: 2px;
    }
  }
  // 二级导航
  .nav-level-two{
    font-size: 14px;
    font-weight: 400;
    color: @color3;
    line-height: 16px;
    letter-spacing: 1px;
  }
  .nav-level-two+.nav-level-two{
    margin-left: 30px;
  }
  .nav-level-two-active{
    color: @colorBg;
    font-weight: 500px;
  }
  // 三级导航
  .nav-level-three{
    font-size: 12px;
    font-weight: 400;
    color: @color3;
    line-height: 16px;
    letter-spacing: 1px;
    padding: 5px 12px;
    background-color: #F5F6F7;
    border-radius: 2px;
  }
  .nav-level-three+.nav-level-three{
    margin-left: 15px;
  }
  .nav-level-three-active{
    background-color: @colorBg;
    font-weight: 500px;
    color: #fff;
  }
  // 固定到最上面
  .top{
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    min-height:100vh;
    background-color: rgba(3,3,3,.5);
  }
  // 固定筛选
  .fixed-filter-bar{
    position: fixed;
    top: 70px;
    width: 100%;
    z-index: 999;
  }
  // 筛选项
  .filter-bar{
    z-index: 99;
    .filter-content{
      min-height: 100px;
      background-color: #fff;
      .filter-content-item{
        position: relative;
        height: 100%;
        width: 100%;
        text-align: center;
        box-sizing: border-box;
        background-color: #F3F4F5;
        overflow: hidden;
        .filter-content-text{
          flex: 0 0 auto;
          // width: 100%;
          font-size: 12px;
          color: #333;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          display: block;
          padding: 0 4px;
        }
        .filter-content-img{
          position: absolute;
          bottom: 0;
          right: 0;
          width: 16px;
          height: 16px;
        }
      }
      .filter-content-item-selected{
        border: 1px solid #16BC83;
        border-radius: 2px;
      }
      // 展开收起
      .filter-content-title{
        display: flex;
        justify-content: space-between;
        align-items: center;
        &>div{
          color: #888;
          font-size: 12px;
          &>svg{
            color: inherit;
            font-size: inherit;
            margin-left: 2px;
          }
        }
      }
    }
  }
  .filter-content-field{
      padding: 0  0 0 10px !important;
      width: 100%;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: space-between;
      &.row{
        margin-top: 16px;
      }
      .cus-field{
        flex: 1;
        height: 36px;
        line-height: 1;
        background: rgba(241, 241, 242, .5);
      }
      .separator{
        margin: 0 16px;
        width: 23px;
        height: 2px;
        background: #B5B7C4;
        border-radius: 1px;
      }
    }
  .sort-content-text{
    width: 100%;
    display: flex;
    align-items: center;
    justify-content:space-between;
    line-height: 22px;
    padding: 10px 0;
    margin: 0 !important;
    border-bottom:1px solid rgba(241, 241, 242, .5);
    &.selected{
      color: #00C8B4 !important;
    }
    .filter-content-selected{
      width: auto;
      height: 14px;
    }
  }
  .contentClass{
    top: 0 !important;
    left: 0 !important;
    transform: none !important;
    width: 100%;
  }
  .scroll-height{
    background-color: #fff;
    max-height: calc(100vh - 120px);
  }
}
</style>
<style>
  .limit-scroll{
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    width: 100vw !important;
    height: 100vh !important;
    overflow: hidden !important;
  }
</style>
